package com.idconfirmsystem.activity;

import java.util.Random;
import java.util.zip.Inflater;

import com.idconfirmsystem.Constants;
import com.idconfirmsystem.R;
import com.idconfirmsystem.handler.AddTaskHandler;
import com.idconfirmsystem.handler.TaskDetailHandler;
import com.idconfirmsystem.model.UserBean;
import com.idconfirmsystem.parse.BranchParse;
import com.idconfirmsystem.remote.TaskApi;
import com.idconfirmsystem.util.FileUtils;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class AddTaskActivity extends Activity {

	// handler
	private Handler handler = new AddTaskHandler(this);

	// 布局元素
	private Element el = new Element();

	private class Element {
		private TextView taskNum;
		private TextView startTime;
		private TextView pilotman;
		private TextView driver;
		private TextView carNum;
		private TextView protectOne;
		private TextView protectTwo;
		private Button sureAdd;
		TextView[] detaiTextViews = { taskNum, startTime, pilotman, driver,
				carNum, protectOne, protectTwo };

		private TableLayout taskTableLayout;

		private EditText date;
	};

	private Context context = AddTaskActivity.this;
	// 运行时临时变量
	private RuntimeObject ru = new RuntimeObject();

	private class RuntimeObject {
		String[] detailString = { "任务编号：9111",
				"出发时间：\n\t\t\t\t2015-08-14 22:54", "业务员：陈   刚", "驾驶员：黄伟鹭",
				"车辆牌号：\n\t\t\t\t闽D86H91", "护卫1\t：汤恒煜", "护卫2\t：林勇利" };

		BranchParse branchParse;
		int mYear;
		int mMonth;
		int mDay;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_task);

		ActionBar ab = getActionBar();
		ab.setDisplayHomeAsUpEnabled(true);
		ab.setHomeButtonEnabled(true);
		setTitle("添加款箱（包）");

		// Bundle bundle = getIntent().getExtras();
		// querySubTaskList(bundle.getString("taskid"));

		initView();
		for (int i = 0; i < 5; i++) {
			addTableRow();
		}

	}

	private void initView() {
		el.taskNum = (TextView) findViewById(R.id.task_num);
		el.startTime = (TextView) findViewById(R.id.task_start_time);
		el.pilotman = (TextView) findViewById(R.id.task_salesman);
		el.driver = (TextView) findViewById(R.id.task_driver);
		el.carNum = (TextView) findViewById(R.id.task_car_num);
		el.protectOne = (TextView) findViewById(R.id.task_protect1);
		el.protectTwo = (TextView) findViewById(R.id.task_protect2);
		el.sureAdd = (Button) findViewById(R.id.sure_add_btn);
		el.sureAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				initDialogView();
				new AlertDialog.Builder(AddTaskActivity.this)
						.setTitle("添加箱(包)")
						.setIcon(R.drawable.ic_launcher)
						.setView(
								View.inflate(AddTaskActivity.this,
										R.layout.add_bag, null))
						.setNegativeButton("取消", null)
						.setPositiveButton("确定", null).show();
			}
		});
		el.taskNum.setText(ru.detailString[0]);
		el.startTime.setText(ru.detailString[1]);
		el.pilotman.setText(ru.detailString[2]);
		el.driver.setText(ru.detailString[3]);
		el.carNum.setText(ru.detailString[4]);
		el.protectOne.setText(ru.detailString[5]);
		el.protectTwo.setText(ru.detailString[6]);

		el.taskTableLayout = (TableLayout) findViewById(R.id.task_tablelayout);
	}

	private void addTableRow() {
		TableRow tr = new TableRow(context);
		TextView tv1 = new TextView(context);
		TextView tv2 = new TextView(context);
		TextView tv3 = new TextView(context);
		TextView tv4 = new TextView(context);
		TextView tv5 = new TextView(context);
		tv1.setText("080100011");
		tv1.setGravity(Gravity.CENTER_HORIZONTAL);
		tv2.setText(randomSixNum());
		tv2.setGravity(Gravity.CENTER_HORIZONTAL);
		tv3.setText("2015-08-31");
		tv3.setGravity(Gravity.CENTER_HORIZONTAL);
		tv4.setText("空箱");
		tv4.setGravity(Gravity.CENTER_HORIZONTAL);
		// tv5.setText("待确认");
		// tv5.setTextColor(getResources().getColor(R.color.red));
		// tv5.setGravity(Gravity.CENTER_HORIZONTAL);
		tv5.setText("删除");
		tv5.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(context, IdConfirmActivity.class);
				startActivity(intent);
			}
		});
		tr.addView(tv1);
		tr.addView(tv2);
		tr.addView(tv3);
		tr.addView(tv4);
		tr.addView(tv5);
		tr.setPadding(0, 8, 0, 8);
		View line = new View(context);
		line.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1));
		line.setBackgroundColor(getResources().getColor(R.color.black));
		el.taskTableLayout.addView(line);
		el.taskTableLayout.addView(tr);
	}

	public String randomSixNum() {
		String str = "";
		str += (int) (Math.random() * 9 + 1);
		for (int i = 0; i < 5; i++) {
			str += (int) (Math.random() * 10);
		}
		return str;
	}

	private void initDialogView() {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View dialogView = inflater.inflate(R.layout.add_bag, null);
		el.date = (EditText) dialogView.findViewById(R.id.bag_time_edit);
		el.date.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				hideIM(v);
				new DatePickerDialog(AddTaskActivity.this, dateSetListener,
						ru.mYear, ru.mMonth, ru.mDay);
			}
		});
		el.date.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus == true) {
					hideIM(v);
					new DatePickerDialog(AddTaskActivity.this, dateSetListener,
							ru.mYear, ru.mMonth, ru.mDay);
				}
			}
		});

	}

	private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			ru.mYear = year;
			String mm;
			String dd;

			if (monthOfYear <= 9) {
				ru.mMonth = monthOfYear + 1;
				mm = "0" + ru.mMonth;
			} else {
				ru.mMonth = monthOfYear + 1;
				mm = String.valueOf(ru.mMonth);
			}

			if (dayOfMonth <= 9) {
				ru.mDay = dayOfMonth;
				dd = "0" + ru.mDay;
			} else {
				ru.mDay = dayOfMonth;
				dd = String.valueOf(ru.mDay);
			}

			ru.mDay = dayOfMonth;

			// .setText(String.valueOf(mYear) + "-" + mm + "-" + dd);
		}
	};

	// 隐藏手机键盘
	private void hideIM(View edt) {
		try {
			InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
			IBinder windowToken = edt.getWindowToken();

			if (windowToken != null) {
				im.hideSoftInputFromWindow(windowToken, 0);
			}
		} catch (Exception e) {

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.task, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void querySubTaskList(final String taskid) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					TaskApi ta = new TaskApi();
					String result = ta.getTaskBranchList(taskid);
					Log.e("getTaskBranchList", result);
					FileUtils.writeByXml(AddTaskActivity.this, result,
							FileUtils.dataUtil() + "_" + taskid + ".xml");
					ru.branchParse = new BranchParse(result);

					handler.sendMessage(handler
							.obtainMessage(Constants.SubTask.UPDATE_SUB_LIST));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	public void updateSubList() {
		initView();
		int length = ru.branchParse.getListLength();
		if (length != 0) {
			for (int i = 0; i < length; i++) {
				addTableRow();
			}
		}

	}
}
